package com.shopping.cart.interpretor;

import com.shopping.cart.vo.UserInfoVo;
import com.shopping.common.constant.AuthServerConstant;
import com.shopping.common.constant.CartConstant;
import com.shopping.common.vo.MemberRespVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

public class CartInterceptor implements HandlerInterceptor {

    public static final ThreadLocal<UserInfoVo> THREAD_LOCAL = new ThreadLocal<>();

    /**
     * 业务执行之前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoVo userInfoVo = new UserInfoVo();
        HttpSession session = request.getSession();
        MemberRespVo member = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (member != null) {
            // 用户登录
            userInfoVo.setUserId(member.getId());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                // user-key
                String name = cookie.getName();
                if (CartConstant.TEMP_USER_COOKIE_NAME.equals(name)) {
                    userInfoVo.setUserKey(cookie.getValue());
                    userInfoVo.setTempUser(true);
                }
            }
        }

        // 没有临时用户就分配一个
        if (StringUtils.isEmpty(userInfoVo.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            userInfoVo.setUserKey(uuid);
        }

        THREAD_LOCAL.set(userInfoVo);
        return true;
    }

    /**
     * 业务执行之后,分配临时用户,让浏览器保存
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoVo userInfoVo = THREAD_LOCAL.get();

        // 是临时用户就放cookie
        if (!userInfoVo.isTempUser()) {
            // 持续延迟临时用户的过期时间
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoVo.getUserKey());
            cookie.setDomain("shopping.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIME_OUT);
            response.addCookie(cookie);
        }

        THREAD_LOCAL.remove();

    }
}
